package com.example.mp.modular.system.handler.EventsHandler;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mp.core.common.JsonUtil;
import com.example.mp.core.common.LogUtil;
import com.example.mp.modular.system.dao.SysUserWechatMapper;
import com.example.mp.modular.system.handler.AbstractHandler;
import com.example.mp.modular.system.model.SysUserWechat;
import com.example.mp.modular.system.service.ISysUserWechatService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutImageMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 用户关注事件
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private ISysUserWechatService wechatService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        getWxUserInfo(wxMessage, weixinService);
        return buildXmlOutMessage(wxMessage, weixinService);
    }

    private void getWxUserInfo(WxMpXmlMessage wxMessage, WxMpService wxService) {
        String lang = "zh_CN"; //语言
        try {
            LogUtil.info(StrUtil.format("wxMessage.getOpenId() 获取到用户openId：" + wxMessage.getOpenId()));
            LogUtil.info(StrUtil.format("wxMessage.getFromUser()获取到用户openId：" + wxMessage.getFromUser()));
            String openId = StringUtils.isEmpty(wxMessage.getOpenId()) ? wxMessage.getFromUser() : wxMessage.getOpenId();

            WxMpUser wxUser = wxService.getUserService().userInfo(openId, lang);
            SysUserWechat sysUserWechat = new SysUserWechat();
            sysUserWechat.setSubscribe(wxUser.getSubscribe() ? 1 : 0);
            sysUserWechat.setOpenid(wxUser.getOpenId());
            sysUserWechat.setNickname(wxUser.getNickname());
            sysUserWechat.setSex(wxUser.getSex());
            sysUserWechat.setCity(wxUser.getCity());
            sysUserWechat.setCountry(wxUser.getCountry());
            sysUserWechat.setProvince(wxUser.getProvince());
            sysUserWechat.setLanguage(wxUser.getLanguage());
            sysUserWechat.setHeadimgurl(wxUser.getHeadImgUrl());
            sysUserWechat.setSubscribeTime(DateUtil.date(wxUser.getSubscribeTime()));
            sysUserWechat.setUnionid(wxUser.getUnionId());
            sysUserWechat.setRemark(wxUser.getRemark());
            sysUserWechat.setGroupid(wxUser.getGroupId());
            sysUserWechat.setTagidList(Arrays.toString(wxUser.getTagIds()));
            sysUserWechat.setSubscribeScene(wxUser.getSubscribeScene());
            sysUserWechat.setQrScene(wxUser.getQrScene());
            sysUserWechat.setQrSceneStr(wxUser.getQrSceneStr());
            sysUserWechat.setUpdatetime(DateUtil.date());
            sysUserWechat.setCreatetime(DateUtil.date());
            boolean isSuccess = wechatService.save(sysUserWechat);
            LogUtil.info("订阅事件：微信公众号获取用户基本信息结果：【" + (isSuccess ? "成功" : "失败") + "】");
        } catch (Exception e) {
            LogUtil.error("订阅事件：微信公众号获取用户基本信息出现异常", e);
        }
    }

    private WxMpXmlOutMessage buildXmlOutMessage(WxMpXmlMessage wxMessage, WxMpService service) {
        try {
            SysUserWechat userWechat = wechatService.getOne(new QueryWrapper<SysUserWechat>().lambda().eq(SysUserWechat::getOpenid, wxMessage.getFromUser()), true);
            if (userWechat != null) {
                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        .toUser(userWechat.getOpenid())
                        .templateId("odcmxnLxZG-XB796371mxk_NA4z12ubIXfv7dTf25uI")
                        .build();
                templateMessage.addData(new WxMpTemplateData("first", "谢谢关注", "#173177"));
                templateMessage.addData(new WxMpTemplateData("keyword1", userWechat.getOpenid(), "#173177"));
                templateMessage.addData(new WxMpTemplateData("keyword2", userWechat.getNickname(), "#173177"));
                templateMessage.addData(new WxMpTemplateData("keyword3", DateUtil.now(), "#173177"));
                templateMessage.addData(new WxMpTemplateData("remark", JsonUtil.toJson(userWechat), "#173177"));
                service.getTemplateMsgService().sendTemplateMsg(templateMessage);
            } else {
                LogUtil.info("未查询到公众号用户的基本信息，openId：" + wxMessage.getFromUser());
            }
        } catch (Exception x) {
            LogUtil.error("响应订阅事件出现异常", x);
        }
        return null;
    }

}
